//index.js
var app = getApp()
Page({
  data: {
    
    goodsList:{
      saveHidden:true,
      totalPrice:0,
      allSelect:true,
      noSelect:false,
      list:[]
    },
    delBtnWidth:120,    //删除按钮宽度单位（rpx）
  },
 
 //获取元素自适应后的实际宽度
  getEleWidth:function(w){
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750/2)/(w/2);  //以宽度750px设计稿做宽度的自适应
      real = Math.floor(res/scale);
      return real;
    } catch (e) {
      return false;
     // Do something when catch error
    }

  },
  initEleWidth:function(){
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth:delBtnWidth
    });
  },
  onLoad: function () {
      this.initEleWidth();
      this.onShow();
  },
  onShow: function(){
    this.getCartList()
  },

  // 获取购物车数据
  getCartList: function (){
    var that = this;
    var shopList = [];
    wx.request({
      url: app.globalData.rootPath + "/m/cart",
      data: {
        token: wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.meta.code === 200 && res.data.data.length > 0) {
          shopList = res.data.data
        }
        that.data.goodsList.list = shopList;
        that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), shopList);
      }
    })
  },
  
  toIndexPage:function(){
      wx.switchTab({
            url: "/pages/index/index"
      });
  },

  touchS:function(e){
    if(e.touches.length==1){
      this.setData({
        startX:e.touches[0].clientX
      });
    }
  },
  touchM:function(e){
    var index = e.currentTarget.dataset.index;
    if(e.touches.length==1){
      var moveX = e.touches[0].clientX;
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var left = "";
      if(disX == 10 || disX < 10){//如果移动距离小于等于0，container位置不变
        left = "margin-left:0px";
      }else if(disX > 10 ){//移动距离大于0，container left值等于手指移动距离
        left = "margin-left:-"+disX+"px";
        if(disX>=delBtnWidth){
          left = "left:-"+delBtnWidth+"px";
        }
      }
      var list = this.data.goodsList.list;
      if(index!="" && index !=null){
        list[parseInt(index)].left = left; 
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
      }
    }
  },

  touchE:function(e){
    var index = e.currentTarget.dataset.index;    
    if(e.changedTouches.length==1){
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var left = disX > delBtnWidth/2 ? "margin-left:-"+delBtnWidth+"px":"margin-left:0px";
      var list = this.data.goodsList.list;
     if(index!=="" && index != null){
        list[parseInt(index)].left = left; 
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);

      }
    }
  },
  delItem:function(e){
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var id_list = that.data.goodsList.list[index].id;
    wx.request({
      url: app.globalData.rootPath + "/m/cart/delete",
      data: {
        token: wx.getStorageSync('token'),
        cart_ids: id_list
      },
      success: function (res) {
        if (res.data.meta.code === 200) {
          wx.showModal({
            title: '提示',
            content: "删除成功",
            showCancel: false
          })
          that.getCartList()
        } else {
          wx.showModal({
            title: '提示',
            content: "删除失败--" + res.data.meta.code,
            showCancel: false
          })
        }
      }
    })
  },

  selectTap:function(e){
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if(index!=="" && index != null){
        list[parseInt(index)].active = !list[parseInt(index)].active ; 
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
      }
   },
   totalPrice:function(){
      var list = this.data.goodsList.list;
      var total = 0;
      for(var i = 0 ; i < list.length ; i++){
          var curItem = list[i];
          if(curItem.active){
            total += parseFloat(curItem.goods_price) * curItem.goods_number;
          }
      }
      total = parseFloat(total.toFixed(2));//js浮点计算bug，取两位小数精度
      return total;
   },
   
   allSelect:function(){
      var list = this.data.goodsList.list;
      var allSelect = false;
      for(var i = 0 ; i < list.length ; i++){
          var curItem = list[i];
          if(curItem.active){
            allSelect = true;
          }else{
             allSelect = false;
             break;
          }
      }
      return allSelect;
   },
  
   noSelect:function(){
      var list = this.data.goodsList.list;
      var noSelect = 0;
      for(var i = 0 ; i < list.length ; i++){
          var curItem = list[i];
          if(!curItem.active){
            noSelect++;
          }
      }
      if(noSelect == list.length){
         return true;
      }else{
        return false;
      }
   },

   //更新数据视图
   setGoodsList:function(saveHidden,total,allSelect,noSelect,list){
      this.setData({
        goodsList:{
          fileServerPath: app.globalData.fileServerPath,
          saveHidden:saveHidden,
          totalPrice: total.toFixed(2),
          allSelect:allSelect,
          noSelect:noSelect,
          list:list
        }
      });
   },
   //将所有的item设置为选择状态
   bindAllSelect:function(){
      var currentAllSelect = this.data.goodsList.allSelect;
      var list = this.data.goodsList.list;
      if(currentAllSelect){
        for(var i = 0 ; i < list.length ; i++){
            var curItem = list[i];
            curItem.active = false;
        }
      }else{
        for(var i = 0 ; i < list.length ; i++){
            var curItem = list[i];
            curItem.active = true;
        }
      }
      this.setGoodsList(this.getSaveHide(),this.totalPrice(),!currentAllSelect,this.noSelect(),list);
   },
   //临时增加购买数量
   jiaBtnTap:function(e){
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if(index!=="" && index != null){
      if (list[parseInt(index)].goods_number < list[parseInt(index)].goods_inventory){
        list[parseInt(index)].goods_number++; 
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
      }else{
        wx.showModal({
          title: '提示',
          content: "该商品库存不足",
          showCancel: false
        })
      }
    }
   },
   //临时减少购买数量
   jianBtnTap:function(e){
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if(index!=="" && index != null){
      if (list[parseInt(index)].goods_number>1){
        list[parseInt(index)].goods_number-- ;
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
      }else{
        wx.showModal({
          title: '提示',
          content: "该商品库存不足",
          showCancel: false
        })
      }
    }
   },
   //编辑删除方法，将所有的数据状态设置为false，显示删除按钮
   editTap:function(){
     var list = this.data.goodsList.list;
     for(var i = 0 ; i < list.length ; i++){
            var curItem = list[i];
            curItem.active = false;
     }
     this.setGoodsList(!this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
   },
  //完成删除显示结算按钮
   saveTap:function(){
     var list = this.data.goodsList.list;
     for(var i = 0 ; i < list.length ; i++){
            var curItem = list[i];
            curItem.active = true;
     }
     this.setGoodsList(!this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
   },
   getSaveHide:function(){
     var saveHidden = this.data.goodsList.saveHidden;
     return saveHidden;
   },
   //删除选择的数据
    deleteSelected:function(){
      var that = this;
      var id_list = "";
      var list = that.data.goodsList.list;
      for(let i = 0 ; i < list.length ; i++){
        if (list[i].active){
          if(id_list === ""){
            id_list += list[i].id;
          }else{
            id_list = id_list+ ","+ list[i].id;
          }
        }
      }
      wx.request({
        url: app.globalData.rootPath + "/m/cart/delete",
        data: {
          token: wx.getStorageSync('token'),
          cart_ids: id_list
        },
        success: function (res) {
          if (res.data.meta.code === 200 ) {
            that.getCartList()
            wx.showModal({
              title: '提示',
              content: "删除成功",
              showCancel: false
            })
          }else{
            wx.showModal({
              title: '提示',
              content: "删除失败--"+res.data.meta.message,
              showCancel: false
            })
          }
        }
      })
    },

    //去生成订单
    toPayOrder:function(){
      var that = this;
      if (this.data.goodsList.noSelect) {
        wx.showModal({
          title: '提示',
          content: "请选择商品",
          showCancel: false
        })
        return;
      };
      var list = that.data.goodsList.list;
      var shopCarInfo = [];
      for (let i = 0; i < list.length; i++) {
        if (list[i].active) {
          shopCarInfo.push(list[i])
        }
      }
      wx.setStorageSync('shopCarInfo', shopCarInfo);
      wx.setStorageSync('orderType', "shopCar");
      wx.navigateTo({
        url: "/pages/to-pay-order/index"
      })
    },
    navigateToPayOrder:function () {
      wx.showLoading();
      wx.hideLoading();
      wx.navigateTo({
        url:"/pages/to-pay-order/index"
      })
    }
})
